/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import data.DataProvider;
import entities.ArtPhoto;
import entities.Artist;
import entities.Artwork;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author bertram
 */
public class StoreWork extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        DataProvider prov = new DataProvider();
        Artwork work = null;
        ArrayList<ArtPhoto> photos = new ArrayList<ArtPhoto>();
        PrintWriter out = response.getWriter();
        try {
            try {
                String str = request.getParameter("data");
                HashMap<String, String[]> params = (HashMap<String, String[]>) request.getParameterMap();

                JSONObject obj = new JSONObject(str);
                JSONArray phtArr = obj.getJSONArray("photos");
                //JSONArray artistArr = obj.getJSONArray("artists");
                if (obj.has("workID") && !obj.getString("workID").isEmpty()) {
                    int workID = Integer.parseInt(obj.getString("workID"));
                    work = prov.getWork(workID);
                } else if (obj.has("kidID") && !obj.getString("kidID").isEmpty()) {
                    int kidID = Integer.parseInt(obj.getString("kidID"));
                    work = prov.getWorkByKidID(kidID);
                } else {
                    work = prov.getWork();
                }
                Artist a = null;
                if (obj.has("kunstnerID") && !obj.getString("kunstnerID").isEmpty()) {
                    a = prov.getArtist(obj.getInt("kunstnerID"));
                } else {
                    String artistName = obj.getString("kunstner");
                    a = prov.getArtist(artistName);
                }
                work.setTitel(obj.getString("titel"));
                work.setTechnique(obj.getString("materialer"));
                work.setDescription(obj.getString("beskrivelse").trim());
                work.setOwner(obj.getString("museum"));
                work.setType(obj.getInt("types"));
                try {
                    if (obj.getInt("aarstal") > 0) {
                        work.setFinished(obj.getInt("aarstal"));
                    }
                } catch (Exception ex) {
                }

                work.addArtist(a);
                for (int i = 0; i < phtArr.length(); i++) {
                    JSONObject o = phtArr.getJSONObject(i);
                    ArtPhoto pht = new ArtPhoto();
                    pht.setProvidedBy(o.getString("providedBy"));
                    pht.setImageID((o.getInt("imageID")));
                    pht.setPublicized(o.getBoolean("publicized"));
                    pht.setPath(o.getString("path"));
                    pht.setType(o.getString("type"));
                    work.addPhoto(pht);
                }
                if (obj.getString("tags").contains(",")) {
                    String tags[] = obj.getString("tags").split(",");
                    for (int i = 0; i < tags.length; i++) {
                        work.addTag(tags[i].toLowerCase());
                    }
                } else if (!obj.getString("tags").isEmpty()) {
                    work.addTag(obj.getString("tags").toLowerCase().trim());
                }
                out.write("{\"status\":\"ok\", \"workID\":" + work.getWorkID() + "}");
                prov.saveWork(work);
            } catch (JSONException ex) {
                out.write("{\"status\":\"kunne ikke læse forespørgsel\"}");
                System.out.println("wwwwwoooooops" + ex.getMessage() + ex.getCause());

            }



        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
